import React,{Component} from "react";
import io from "socket.io-client";
import {ChatList} from "./chatList";
import "../index.css";

const socket = io('http://119.23.243.253:3004');

socket.on('connect', (e) => {
  
});

export class Chat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      textList: []
    }
  }

  componentDidMount() {
    const {textList} = this.state;
    let newTextList = textList;
    socket.on('chatMsg', (msg) => {
      newTextList.push(msg);
      this.setState({textList: newTextList});
    })
  }
  
  chatMsg = (e) => {
    e.preventDefault();
    const {text} = this.state;
    try {
      socket.emit('chatMsg', text, (e) => {
        console.log(e)
      });
    } catch (error) {
      console.log(error)
    }
  }

  handleText = (e) => {
    this.setState({text: e.target.value});
  }
  
  render() {
    const {text, textList} = this.state;
    return(
      <div className="wraper">
        <ChatList textList={textList}/>
        <form className="chatBox" onSubmit={this.chatMsg}>
          <input type="text" value={text} onChange={this.handleText} className="chatInput"/>
          <button className="chatBtn">发送</button>
        </form>
      </div>
    )
  }
}